import {
  createSession,
  saveUser
} from '@/utils/session.js'
import {
  showToast
} from '@/utils/feedback.js'

import { get, post } from '@/utils/request.js'
import { Urls } from '@/utils/urls.js'

const KEYS = ['hasPhone', 'hasAvatar', 'hasLogin', 'hasRegister', 'sessionId', 'userId', 'nickName', 'avatarUrl']

const getDefaultState = () => {
  const result = {}
  KEYS.map(key => {
    result[key] = uni.getStorageSync(key) || ''
  })
  return result
}

const state = getDefaultState()

const mutations = {
  SET_AUTH: (state, info) => { // 设置token
    KEYS.map(key => {
      if (typeof info[key] !== 'undefined') {
        state[key] = info[key]
        uni.setStorageSync(key, info[key])
      }
    })
  }
}

const actions = {
  getAuth({ state }) { // 获取用户授权信息
    return new Promise(resolve => {
      if (state.hasLogin) { // 已授权，直接返回
        resolve({
          sessionId: state.sessionId,
          nickName: state.nickName,
          avatarUrl: state.avatarUrl
        })
      } else { // 未授权，跳转到登录页
        uni.navigateTo({
          url: "/pages/login/login"
        })
      }
    })
  },
  modifyAuth({ state, commit }, authInfo) {
    commit('SET_AUTH', authInfo);
  },
  async buildSession({ state, commit, dispatch }, jsCode) {
    const url = Urls.getApi("sessionCode");
    const res = await get(url, {
      needAuth: false,
      data: {
        jsCode
      },
    })

    let sesCode = res.module;
    // console.log("[user-sore]app-session-code:", sesCode);
    const { code, phone, avatar, register, userInfo = {} } = sesCode;
    commit('SET_AUTH', {
      hasLogin: true,
      sessionId: code,
      hasPhone: phone,
      hasAvatar: avatar,
      hasRegister: register,
      userId: userInfo.userId || '',
      nickName: userInfo.nickName || '',
      avatarUrl: userInfo.avatarUrl || '',
    })
    
    return new Promise((resolve, reject) => {
      resolve(res);
    })
  },
  login({ state, commit, dispatch }) {
    return new Promise((resolve, reject) => {    
      uni.login({
        provider: 'weixin',
        // #ifdef MP-ALIPAY
        scopes: 'auth_user', //支付宝小程序需设置授权类型
        // #endif
        success: (res) => {
          // console.log("[user-sore]app-user-login res:", res);
          dispatch('buildSession', res.code)
          .then(r => {
            //console.log('33333:', r)
            resolve(r);
          })
        },
        fail: (err) => {
          console.log('app login fail:', err);
          reject(err);
        }
      });
    })
  },
  logout({ commit, dispatch }) { // 退出登录
    commit('SET_AUTH', {
      hasLogin: false,
      sessionId: '',
      userId: '',
      nickName: '',
      avatarUrl: ''
    })
    return Promise.resolve()
  },
  getLocalUser({ dispatch }) { // 本地获取用户信息
    return new Promise(resolve => {
      dispatch('getAuth').then(res => {
        resolve(res)
      })
    })
  },
  getUserInfo({ dispatch }) {
    if (uni.getUserProfile) {
      uni.redirectTo({
        url: "/pages/login/login"
      })
      return;
    }
    return new Promise((resolve, reject) => {
      // console.log("[user-store] getUserInfo")
      uni.getUserInfo({
        provider: 'weixin',
        success: (result) => {
          let user = result.userInfo;
          resolve(user);
        },
        fail: (error) => {
          // console.log('[user-store] getUserInfo fail', error);
          uni.redirectTo({
            url: "/pages/login/login"
          })
        }
      });
    })
  },
  getAndSaveUser({ state, commit, dispatch }) {
    return new Promise((resolve, reject) => {
      dispatch('getUserInfo').then(res => {
        if (!res) {
          uni.redirectTo({
            url: "/pages/login/login"
          })
          return
        }
        if (!state.hasRegister) {
          let user = {
            nickName: res.nickName,
            avatar: res.avatarUrl,
            city: res.city || "",
            country: res.country || "",
            gender: res.gender || "",
            language: res.language || "zh_CN",
            province: res.province || "",
          }
          saveUser(user).then(r => {
            commit('SET_AUTH', {
              hasRegister: true
            })
          });
        }
        if (!state.hasPhone) {
          uni.redirectTo({
            url: "/pages/login/login"
          })
        } else {
          resolve(res);
        }
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
